/**
 * @Description:
 * @Author bianpengfei
 * @create 2022/9/16 13:08
 */
import { Decimal } from '@bianpengfei/utils'

/**
 * 格式化label文字，换行
 * @param label 文字
 * @param len 按照每隔len个文字换行
 * @returns {string|*}
 */
export const formatAxisLabel = (label, len = 6) => {
  if (label.length > len) {
    let newParamsName = ''
    let paramsNameNumber = label.length
    let provideNumber = len
    let rowNumber = Math.ceil(paramsNameNumber / provideNumber)
    if (paramsNameNumber > provideNumber) {
      for (let p = 0; p < rowNumber; p++) {
        let tempStr = ''
        let start = p * provideNumber
        let end = start + provideNumber
        if (p == rowNumber - 1) {
          tempStr = label.substring(start, paramsNameNumber)
        } else {
          tempStr = label.substring(start, end) + '\n'
        }
        newParamsName += tempStr
      }
    } else {
      newParamsName = label
    }
    return newParamsName
  }
  return label
}

/**
 * 格式化数字
 * @param num 数字
 * @param fixedLen 保留数字小数长度
 * @param force  true 如果动态的根据值，值不超过1w，就返回整个数值，不需要格式化   false：强行格式化成w，
 * @param type 格式化单位， w：万  k：千 如果是w，小于100
 * @returns {*}
 */
export const formatNum = (num = 0, fixedLen = -1, force = false, type = 'W') => {
  if (isNaN(num) || num === '0') num = 0
  const wFn = (num = 0) => {
    if (!force && +num < 10 ** 4 && +num > -(10 ** 4)) return fixedLen == -1 ? +num : +num.toFixed(fixedLen)
    const decNum = new Decimal(+num).div(10 ** 4)
    const decNumFixed = fixedLen == -1 ? +decNum.toFixed() : +decNum.toFixed(fixedLen)
    return decNumFixed == 0 ? 0 : `${decNumFixed}w`
  }
  const kFn = (num = 0) => {
    if (!force && +num < 10 ** 3 && +num > -(10 ** 3)) return fixedLen == -1 ? +num : +num.toFixed(fixedLen)
    const decNum = new Decimal(+num).div(10 ** 3)
    const decNumFixed = fixedLen == -1 ? `${decNum.toFixed()}k` : `${decNum.toFixed(fixedLen)}k`
    return decNumFixed == 0 ? 0 : `${decNumFixed}k`
  }
  const conf = {
    W: wFn,
    K: kFn
  }
  return conf[type.toString().toUpperCase()]?.(num) || num
}

/**
 * 计算比率，得出占比、上升/下降了多少比率
 * @param data
 */
export const calRate = (data = { cur: 0, last: 0 }) => {
  const diffDecimal = new Decimal(+data.cur).sub(+data.last)
  const compareRateNum = data.cur ? diffDecimal.abs().div(+data.last) : new Decimal(0)
  return {
    cur: data.cur,
    last: data.last,
    trend: +diffDecimal.toFixed() > 0 ? 'up' : +diffDecimal.toFixed() < 0 ? 'down' : '',
    compareRate: `${compareRateNum.mul(100).toFixed(2)}%`,
    compareRateNum: +compareRateNum.toFixed(4),
    compareNum: +diffDecimal.toFixed()
  }
}
